<template>
  <div class="plan-edit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑套餐' : '添加套餐' }}</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px" 
        v-loading="loading"
      >
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </el-form-item>
        
        <el-form-item label="套餐价格" prop="price">
          <el-input-number 
            v-model="form.amount" 
            :min="0" 
            :precision="2"
            :step="10"
            controls-position="right"
          />
          <span class="tip-text">元</span>
        </el-form-item>
        
        <el-form-item label="原价" prop="origin_price">
          <el-input-number 
            v-model="form.origin_price" 
            :min="0" 
            :precision="2"
            :step="10"
            controls-position="right"
          />
          <span class="tip-text">元（不填则不显示原价）</span>
        </el-form-item>
        
        <el-form-item label="套餐描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入套餐描述"
          />
        </el-form-item>
        
        <el-form-item label="套餐详情" prop="details">
          <el-input 
            v-model="form.details" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入套餐详情，支持HTML格式"
          />
          <div class="tip-text">* 套餐详情支持HTML格式，每行可以使用&lt;li&gt;标签包裹表示列表项</div>
        </el-form-item>
        
        <el-form-item label="有效期" prop="expire_days" v-if="form.type !== 'permanent'">
          <el-input-number 
            v-model="form.expire_days" 
            :min="1" 
            :precision="0"
            controls-position="right"
          />
          <span class="tip-text">天</span>
        </el-form-item>
        <el-form-item label="使用次数" prop="expire_days" v-if="form.type !== 'permanent'">
          <el-input-number 
            v-model="form.times" 
            :min="1" 
            :precision="0"
            controls-position="right"
          />
          <span class="tip-text">次</span>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="form.sort" 
            :min="0" 
            :max="99" 
            controls-position="right"
          />
          <span class="tip-text">数字越小越靠前</span>
        </el-form-item>
        
        <el-form-item label="是否推荐" prop="is_recommend">
          <el-switch 
            v-model="form.is_recommend" 
            :active-value="1" 
            :inactive-value="0"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getPlanDetail, addPlan, updatePlan } from '@/api/plans'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 获取路由中的ID参数
const planId = computed(() => {
  return parseInt(route.params.id) || 0
})

// 判断是编辑还是新增
const isEdit = computed(() => {
  return planId.value > 0
})

// 表单数据
const form = reactive({
  name: '',
  times: 1,
  amount: 0,
  origin_price: 0,
  description: '',
  details: '',
  expire_days: 30,
  sort: 0,
  is_recommend: 0,
  status: 1
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入套餐价格', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入套餐描述', trigger: 'blur' }
  ],
  details: [
    { required: true, message: '请输入套餐详情', trigger: 'blur' }
  ],
  expire_days: [
    { required: true, message: '请输入有效期天数', trigger: 'blur' }
  ]
})

// 监听套餐类型变化，自动调整有效期
watch(() => form.type, (newType) => {
  if (newType === 'month') {
    form.expire_days = 30
  } else if (newType === 'quarter') {
    form.expire_days = 90
  } else if (newType === 'year') {
    form.expire_days = 365
  } else if (newType === 'permanent') {
    form.expire_days = 0
  }
})

// 返回列表页
const goBack = () => {
  router.push('/plan/list')
}

// 获取套餐详情
const getDetail = async () => {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    const res = await getPlanDetail(planId.value)
    if (res.code === 0) {
      // 更新表单数据
      Object.assign(form, res.data)
    } else {
      ElMessage.error(res.message || '获取套餐详情失败')
    }
  } catch (error) {
    console.error('获取套餐详情失败', error)
    ElMessage.error('获取套餐详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      let res
      if (isEdit.value) {
        // 编辑
        res = await updatePlan(planId.value, form)
      } else {
        // 新增
        res = await addPlan(form)
      }
      
      if (res.code === 0) {
        ElMessage.success(`${isEdit.value ? '编辑' : '添加'}成功`)
        goBack()
      } else {
        ElMessage.error(res.message || `${isEdit.value ? '编辑' : '添加'}失败`)
      }
    } catch (error) {
      console.error(`${isEdit.value ? '编辑' : '添加'}失败`, error)
      ElMessage.error(`${isEdit.value ? '编辑' : '添加'}失败`)
    } finally {
      loading.value = false
    }
  })
}

onMounted(() => {
  getDetail()
})
</script>

<style scoped>
.plan-edit-container {
  height: 100%;
  padding: 20px;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.form-footer {
  text-align: right;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper), 
:deep(.el-textarea__wrapper),
:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-switch) {
  --el-switch-on-color: #409EFF;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-left: 0;
  padding-right: 0;
}

.tip-text {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
</style> 